<template>
	<!-- 创作 -->
	<view class="">

		<view class="" v-if="currentFramerItem.home_code">
			<view class="author-header pd20" style="background: linear-gradient(180deg,#0081ff,#069cff 10%,rgba(255,214,41,.01) 90%);
		}">
				<view class="top" style="display: flex;align-items: center;">
					<view class="" style="max-width:80%;white-space: nowrap;overflow: auto;">
						<image :src="item.home_profile"
							:style="creationUserIndex == index?'border:5rpx solid #ee8172':''"
							@tap="tapCuTcreation(item,index)" v-for="(item,index) in framerList"
							style="width: 100rpx;height: 100rpx;background: #ccc;border-radius: 50%;margin-right: 20rpx;"
							mode="" :key="index"></image>
					</view>
					<view class="" @click="showModal"
						style="width: 20%;display: flex;align-items: center;justify-content: center;">
						<image src="/static/creation/add.png" style="width: 100rpx;height: 100rpx;" alt="">
					</view>
				</view>

				<view class="creation-user">
					<view class="left">
						<image :src="currentFramerItem.home_profile"
							style="width: 100rpx;height: 100rpx;background: #ccc;border-radius: 50%;" mode="">
						</image>
						<view class="">
							<view class="name">
								{{currentFramerItem.home_name}}
							</view>
							<view class="num">
								口令：{{currentFramerItem.home_code}}
							</view>
						</view>
					</view>
					<view class="right">
						<view class="">
							<!-- <image src="/static/creation/icon1.png" style="width: 64rpx;height: 48rpx;" mode=""></image> -->
							<image @tap="toAudit" src="/static/creation/icon2.png" style="width: 64rpx;height: 48rpx;"
								mode=""></image>
							<image @click="showModal('set')" src="/static/creation/icon3.png"
								style="width: 64rpx;height: 48rpx;" mode=""></image>
							<!-- <image src="/static/creation/icon1.png"  alt=""> -->
						</view>
					</view>
				</view>

			</view>

			<view class="img-cont-box pd20">
				<view class="creation-box">
					<view class="left">
						<view class="">
							全部作品({{worksCount}})
						</view>
					</view>
					<!-- <view class="right">
						<view class="" @tap="showModal">
							声明
						</view>
					</view> -->
				</view>
				<view class="" style="margin-bottom: 30rpx;">
					<imgTypeTab :imgTypeList="imgTypeList" ref="imgTypeTab" @tabSelect="tabSelect"></imgTypeTab>

				</view>

				<template v-if="currentImgTypeItem.name == '头像' || currentImgTypeItem.name == '表情包' ">
					<worksList :isOpt="isOpt" @stickImg="stickImg" :currentImgs="imgsList" :itemStyle="{
						width: '25%',
						height: '150rpx'
					}"></worksList>

				</template>
				<template v-if="currentImgTypeItem.name == '动态壁纸' || currentImgTypeItem.name == '壁纸' ">
					<worksList :isOpt="isOpt" @stickImg="stickImg" :currentImgs="imgsList" :itemStyle="{
						'width':'33.33%',
						'height':'350rpx',
					}"></worksList>
				</template>

				<template v-if="currentImgTypeItem.name == '背景图' ">
					<worksList :isOpt="isOpt" @stickImg="stickImg" :currentImgs="imgsList" :itemStyle="{
						width:'50%',
						'height':'200rpx',
					}"></worksList>
				</template>


				<dataNo v-if="imgsList.length == 0"></dataNo>

				<view class="" style="text-align: center;margin-top: 30rpx;" v-if="pageIndex != 1">
					{{none}}
				</view>

			</view>

			<view class="" style="height: 200rpx;">

			</view>


			<view class="bottom-btn-up" style="background: #fff;" v-if="!isOpt">
				<view class="bottom-btn-item" @tap="isOpt = true">
					<image src="/static/creation/move.png" style="width: 28rpx;height: 28rpx;" mode=""></image>
					<view class="">
						批量管理
					</view>
				</view>

				<view class="" style="width: 0.5rpx;height: 30rpx;background: #ff6d59;">

				</view>

				<view class="bottom-btn-item" @tap="tapToUpImgs">
					<image src="/static/creation/up_icon.png" mode="" style="width: 28rpx;height: 28rpx;"></image>
					<view class="">
						上传图片
					</view>
				</view>
			</view>


			<view class="bottom-btn-up" style="background: #fff;" v-if="isOpt">
				<view @tap="item.batchOpt(item,index)" class="bottom-btn-item" v-for="(item,index) in batchOptList"
					:key="index">
					<image src="/static/creation/move.png" style="width: 28rpx;height: 28rpx;" mode=""></image>
					<view class="">
						{{item.name}}
					</view>
				</view>

				<view class="" style="width: 0.5rpx;height: 30rpx;background: #ff6d59;">

				</view>

			</view>




			<view class="cu-modal" :class="modalName=='Modal'?'show':''">
				<view class="cu-dialog bg-white">
					<view class="cu-bar">
						<view style="padding: 0 50rpx;font-size: 40rpx;font-weight: bold;color: #000;">新建主页</view>
						<view class="action" @tap="hideModal">
							<text class="cuIcon-close text-red"></text>
						</view>
					</view>
					<view class="nwe-home-form">
						<view class="nwe-home-item">
							<view class="left">
								主页名称
							</view>
							<view class="right">
								<input type="text" v-model="framerForm.home_name" placeholder="请输入主页名称">
							</view>
						</view>
						<view class="nwe-home-item">
							<view class="left">
								主页头像
							</view>
							<view class="right">
								<image @tap="upImg" :src="framerForm.home_profile"
									style="margin-right:20rpx;border-radius: 50%;width: 150rpx;height: 150rpx;background: #ccc;"
									mode=""></image>
								<view class="opt-btn-box" @tap="upImg">
									上传头像
								</view>
							</view>

						</view>
						<view class="nwe-home-item" v-if="showModalType != 'set'">
							<view class="left">
								页面口令
							</view>
							<view class="right" style="position: relative;">
								<input type="number" v-model="framerForm.home_code" style="padding-right: 180rpx;"
									placeholder="请输入主页名称">
								<view @tap="detectionCode" class="opt-btn-box"
									style="border: 1rpx solid #ff6d59; position: absolute;right: 20rpx;top: 50%;transform: translateY(-50%);">
									立即检测
								</view>
							</view>
						</view>
					</view>
					<view class="nwe-home-form-bottom">
						<view class="left" @tap="hideModal">
							取消
						</view>
						<view class="right" @tap="affirmAddFramer">
							确认
						</view>
					</view>
				</view>


			</view>


		</view>
		<view class=" " v-else>
			<view class="">
				<slideshow :swiperList="swiperList"></slideshow>
			</view>
			<view class="mt-50 cu-dialog bg-white" style="width: 100%;">

				<view class="nwe-home-form">
					<view class="nwe-home-item">
						<view class="left">
							主页名称
						</view>
						<view class="right">
							<input type="text" v-model="framerForm.home_name" placeholder="请输入主页名称">
						</view>
					</view>
					<view class="nwe-home-item">
						<view class="left">
							主页头像
						</view>
						<view class="right">
							<image @tap="upImg" :src="framerForm.home_profile"
								style="margin-right:20rpx;border-radius: 50%;width: 150rpx;height: 150rpx;background: #ccc;"
								mode=""></image>
							<view class="opt-btn-box" @tap="upImg">
								上传头像
							</view>
						</view>

					</view>
					<view class="nwe-home-item" v-if="showModalType != 'set'">
						<view class="left">
							页面口令
						</view>
						<view class="right" style="position: relative;">
							<input type="number" v-model="framerForm.home_code" style="padding-right: 180rpx;"
								placeholder="请输入主页名称">
							<view @tap="detectionCode" class="opt-btn-box"
								style="border: 1rpx solid #ff6d59; position: absolute;right: 20rpx;top: 50%;transform: translateY(-50%);">
								立即检测
							</view>
						</view>
					</view>
				</view>
				<view class="" style="margin-top: 300rpx;">
					<view class="nwe-home-form-bottom">
						<!-- <view class="left" @tap="hideModal">
							取消
						</view> -->
						<view class="right" @tap="affirmAddFramer">
							确认
						</view>
					</view>
				</view>
			</view>

		</view>

	</view>
</template>

<script>
	import worksList from "@/components/common/works-list.vue"
	import imgTypeTab from "@/components/common/img-type-tab.vue"
	import slideshow from "@/components/common/slideshow.vue"
	var _this = ''
	export default {
		components: {
			worksList,
			imgTypeTab,
			slideshow
		},
		data() {
			return {
				delList: [],
				currentDelIndex: 0,
				isOpt: false,
				batchOptList: [{
						icon: "",
						name: "退出",
						batchOpt(item, index) {
							_this.isOpt = false
						}
					},
					{
						icon: "",
						name: "置顶",
						async batchOpt(item, index) {
							_this.imgsList.forEach(item => {
								if (item.active) {
									_this.stick(item)
									// item.is_top = 1
								}
							})


							setTimeout(() => {
								_this.getImgsList(true)
							}, 500)



						}
					},
					{
						icon: "",
						name: "删除",
						async batchOpt(item, index) {
							let ids = _this.imgsList.map(item => {
								if (item.active) {
									return item._id
								}
							}).filter(item => {
								return item
							})
							var data = await _this.$api.delDataById({
								dbName: "wx_imgs",
								ids: ids
							})


							setTimeout(() => {
								_this.getImgsList(true)
							}, 500)



						}
					}
				],

				showModalType: "",
				// 图片列表
				imgsList: [],
				// 当前图片类型数据
				currentImgTypeItem: {},
				// 图片类型列表
				imgTypeList: [],
				// 当前创作数据
				currentFramerItem: {
					imgs_list: []
				},
				// 创作者列表
				framerList: {},
				// 添加创作者提交数据
				framerForm: {
					home_name: '',
					home_profile: '',
					home_code: ''
				},

				creationUserIndex: 0,
				creationUserList: [{

					},

				],
				currentImgs: {},
				modalName: "",

				img_list: [],
				worksCount: 0,
				none: "",
				swiperList: [],
				watchImgsList: [],
				params: {
					pageIndex: 1,
					pageSize: 20,
				},
				total: 0,
			}
		},
		watch: {
			imgsList: {
				deep: true, //true为进行深度监听,false为不进行深度监听
				handler(newVal) {
					this.watchImgsList = newVal.filter(item => {
						return item.active && item.is_top != 0
					})

					if (this.watchImgsList.length != 0) {
						this.batchOptList[1].name = '取消置顶'
						this.batchOptList = Object.assign([], this.batchOptList)
					} else {
						this.batchOptList[1].name = '置顶'
						this.batchOptList = Object.assign([], this.batchOptList)

					}

				}
			}
		},
		onLoad() {
			
		},
	
		onShow() {
			var uni_id_token = uni.getStorageSync('uni_id_token')
			if(!uni_id_token){
				uni.navigateTo({
					url:"/pages/my/login/login"
				})
				return
			}
			
			
			_this = this
			var userInfo = uni.getStorageSync('user') || {}
			if (!userInfo._id) {
				this.currentFramerItem = {}
				this.framerForm = {
					home_name: '',
					home_profile: '',
					home_code: ''
				}
			
			}
			this.pageIndex = 1
			this.none = ''
			this.imgsList = []
			this.init()
			this.getFramer()
			this.getBanner()
			this.getImgTypeList()
		},
		onReachBottom() {
			// this.adUnitIdbanner = this.advertisingData1(this.advertisingDataType.bannerList)
			if (this.total > this.params.pageIndex * this.params.pageSize) {
				this.params.pageIndex++;
				this.getImgsList();
			}
		},
		onPullDownRefresh() {
			this.getImgsList(true)
		},
		methods: {
			// 取消置顶 、 置顶
			async stick(item, index) {
				var data = await this.$api.setData({
					dbName: "wx_imgs",
					whereJson: {
						framer_id: item.framer_id,
						_id: item._id
					},
					dataJson: {
						is_top: this.watchImgsList.length != 0 ? 0 : 1
					}
				}, true)
			},
			toAudit() {
				uni.navigateTo({
					url: '/pages/creation/audit?code=' + this.currentFramerItem.home_code
				})
			},
			stickImg(type, item, index) {
				if (type == 'del') {
					this.imgsList.splice(index, 1)
					let list = this.imgsList
					this.getCount()
				}
				if (type == 'stick') {
					this.getImgsList(true)
				}

				if (type == 'optImg') {
					item.active = !item.active
					this.imgsList = Object.assign([], this.imgsList)
				}



				// this.pageIndex = 1
				// this.none = ''
				// this.imgsList = []
				// this.getImgsList()
			},
			async getBanner() {
				var data = await this.$api.getData({
					dbName: "wx_banner",
					pageIndex: 1,
					pageSize: 10,
					sortRule: [{
						name: 'sort',
						type: 'desc'
					}]
				}, true)
				this.swiperList = data.rows
			},
			async getCount() {
				var userInfo = uni.getStorageSync('user') || {}
				var data = await this.$api.getCount({
					dbName: "wx_imgs",
					whereJson: {
						framer_id: this.currentFramerItem.home_code || '',
						user_id: userInfo.openid || '',
					}
				})
				this.worksCount = data.num
			},
			reset(refresh) {
				this.none = ''
				this.params.pageIndex = 1
				if (refresh) {
					this.imgsList = []
				}
			},
			// 获取图片
			async getImgsList(refresh) {

				var userInfo = uni.getStorageSync('user') || {}
				if (refresh) {
					this.reset()
				}
				var data = await this.$api.getData({
					dbName: "wx_imgs",
					sortRule: [{
						"name": "is_top",
						"type": "desc"
					}, ],
					whereJson: {
						img_type: this.currentImgTypeItem.type || '',
						framer_id: this.currentFramerItem.home_code || '',
						user_id: userInfo.openid || '',
						status: 1
					},
					pageIndex: this.params.pageIndex,
					pageSize: this.currentImgTypeItem.type == 1 || this.currentImgTypeItem.type == 4 ? 30 : 10
				}, true)
				if (refresh) {
					this.reset(true)
				}
				uni.stopPullDownRefresh();
				if (data.rows.length != 0) {
					this.imgsList = [...this.imgsList, ...data.rows]
					this.total = data.total
				} else {
					this.none = '没有数据了'
				}
			},
			// 获取创作者
			async getFramer() {
				var userInfo = uni.getStorageSync('user') || {}
				var data = await this.$api.getData({
					dbName: "wx_framer",
					whereJson: {
						framer_id: userInfo.openid || '',
					}
				}, true)

				this.framerList = data.rows
				if (this.framerList.length != 0) {
					this.currentFramerItem = this.framerList[this.creationUserIndex]
					this.getCount()
				}
			},
			// 获取图片类型列表
			async getImgTypeList() {
				var data = await this.$api.getData({
					dbName: "wx_img_type",
					sortRule: [{
						"name": "index",
						"type": "asc"
					}]
				})
				this.imgTypeList = data.rows
				setTimeout(() => {
					if (this.imgTypeList[0] && this.$refs['imgTypeTab']) {
						this.currentImgTypeItem = this.imgTypeList[this.$refs['imgTypeTab'].TabCur]
						this.getImgsList(true)
					}
				}, 500)
			},
			// 上传图片
			upImg() {

				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					loop: true,
					success: res => {
						uni.showLoading({
							title: "上传中"
						})
						res.tempFiles.forEach(async (item, index) => {

							const result = await uniCloud.uploadFile({
								filePath: item.path,
								cloudPath: item.name,
								onUploadProgress: function(progressEvent) {
									console.log(progressEvent);
									var percentCompleted = Math.round(
										(progressEvent.loaded * 100) /
										progressEvent
										.total
									);
								}
							});


							this.framerForm.home_profile = result.fileID;
							if (res.tempFilePaths.length - 1 == index) {
								uni.hideLoading()
							}
						})


						// console.log(JSON.stringify(res.tempFilePaths));
						// var upImgList = res.tempFilePaths;

						// console.log(upImgList);
						// console.log(upImgList[0]);

					}
				});
			},
			// 检测页面口令
			async detectionCode(cb) {
				var res = await this.$api.getCount({
					dbName: "wx_framer",
					whereJson: {
						home_code: this.framerForm.home_code
					}
				})
				console.log(res)
				if (res.num != 0) {
					uni.showToast({
						title: "口令已使用，请换其他口令",
						icon: "none"
					})
					return
				}
				if (typeof cb == 'function') {
					cb()
					return
				}
				uni.showToast({
					title: "可以使用",
					icon: "none"
				})
			},
			// 确认添加创作
			async affirmAddFramer() {
				var userInfo = uni.getStorageSync('userInfo') || {}
				let framerForm = this.framerForm
				var home_name = this.$U.reg.isEmpty(framerForm.home_name, '主页名称不能为空')

				if (home_name) {
					return
				}
				var home_profile = this.$U.reg.isEmpty(framerForm.home_profile, '主页头像不能为空')

				if (home_profile) {
					return
				}
				if (this.showModalType != 'set') {
					var home_code = this.$U.reg.isEmpty(framerForm.home_code, '页面口令不能为空')

					if (home_code) {
						return
					}
				}
				if (this.showModalType == 'set') {
					this.setFramer()
					return
				}
				this.detectionCode(async () => {
					this.addFramer()
				})

			},
			async addFramer() {
				var userInfo = uni.getStorageSync('user') || {}
				var data = await this.$api.addData({
					dbName: "wx_framer",
					dataJson: {
						...this.framerForm,
						framer_id: userInfo.openid || '',
						imgs_list: [],
						is_rd: 0,
					}
				}, true)
				if (data.code == 0) {
					uni.showToast({
						title: "创建成功"
					})
					this.getFramer()
					setTimeout(() => {
						this.hideModal()
					}, 500)
				}

			},
			async setFramer() {
				var data = await this.$api.setData({
					dbName: "wx_framer",
					dataJson: {
						home_profile: this.framerForm.home_profile,
						home_name: this.framerForm.home_name,
						add_data: this.framerForm.add_data
					},
					whereJson: {
						_id: this.framerForm._id
					}
				})
				if (data.code == 0) {
					uni.showToast({
						title: "创建成功"
					})
					this.getFramer()
					setTimeout(() => {
						this.hideModal()
					}, 500)
				}

			},
			// 图片类型tab
			tabSelect(item) {
				this.currentImgTypeItem = item
				this.getImgsList(true)
			},
			// 上传图片
			tapToUpImgs() {
				uni.navigateTo({
					url: "/pages/creation/up-img?framer_id=" + this.currentFramerItem.home_code + '&framer_name=' +
						this.currentFramerItem.home_name
				})
			},
			// 切换创作者口令用户
			tapCuTcreation(item, index) {
				this.creationUserIndex = index
				this.currentFramerItem = item
				this.getImgsList(true)

			},
			init() {
				if (this.img_list[0]) {
					this.currentImgs = this.img_list[0]

				}
			},

			showModal(type) {
				this.modalName = "Modal"
				this.showModalType = type
				if (type == 'set') {
					this.framerForm = JSON.parse(JSON.stringify(this.currentFramerItem))
					delete this.framerForm.home_code
				} else {
					this.framerForm = {}
				}
			},
			hideModal(e) {
				this.modalName = null
			},
		}
	}
</script>
<style>
	page {
		background: #fff;
	}
</style>
<style lang="scss" scoped>
	.bottom-btn-up {
		border: 1rpx solid #ff8f7f;
		display: flex;
		align-items: center;
		position: fixed;
		bottom: 150rpx;
		left: 50%;
		transform: translateX(-50%);
		border-radius: 50rpx;

		.bottom-btn-item {
			color: #ff675c;
			white-space: nowrap;

			image {
				margin-right: 5rpx;
			}

			padding: 20rpx 20rpx;
			display: flex;
			align-items: center;
		}
	}

	.creation-box-cont {}

	.nwe-home-form-bottom {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 20rpx;

		view {
			color: #fff;
			margin: 0 20rpx;
			padding: 25rpx 80rpx;
			border-radius: 20rpx;
			background: #ff6d59;
		}

		.left {
			color: #50536e;
			background: #f5f6fa
		}
	}

	.nwe-home-form {
		font-size: 28rpx;
		color: #000;
		padding: 0 50rpx;

		.nwe-home-item {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;

			.opt-btn-box {
				display: flex;
				align-items: center;
				justify-content: center;
				background: #fff0ee;
				color: #ff806f;
				border-radius: 20rpx;
				padding: 10rpx 10rpx;
			}

			.right {
				margin-left: 30rpx;
				display: flex;
				align-items: center;

				input {
					text-align: left;
					width: 430rpx;
					height: 90rpx;
					background: #f5f6fa;
					padding: 5rpx 30rpx;
					font-size: 28rpx;
					border-radius: 30rpx;
				}
			}
		}
	}

	.img-cont-box {
		background: #fff;
		border-radius: 50rpx;
		position: relative;
		top: -70rpx;

	}



	.creation-box {
		padding-top: 30rpx;
		margin-top: 35rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.left>view,
		.right>view {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 25rpx;
			padding: 10rpx 15rpx;
			background: linear-gradient(to right, #9dd8fe, #20a6ff);
			color: #fff;
			border-radius: 50rpx;
		}

		.right>view {
			background: #fff;
			color: #6e5957;
		}
	}


	.author-header {
		padding-top: 30rpx;
		background: url('../../static/creation/header-bg.png') no-repeat;
		background-size: 100% 100%;


		.creation-user {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 0 60rpx 0;



			.left {
				display: flex;
				align-items: center;

				image {
					margin-right: 15rpx;
				}

				.name {
					margin-bottom: 10rpx;
					font-size: 26rpx;
					color: #784f55;
				}

				.num {
					font-size: 25rpx;
					color: #806065;
				}
			}


			.right {
				image {
					margin-left: 20rpx;
				}
			}

		}

	}
</style>